/**
 * API操作组合函数
 * 负责所有与API相关的操作逻辑
 */
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';

export function useApiOperations(route, ActionAPI, MenuAPI, ApiAPI, LangAPI) {
  // 是否显示载入效果
  const loading = ref(false);

  /**
   * 获取表单数据（编辑模式）
   * @param {number} id - 记录ID
   */
  const getFormData = async (id) => {
    loading.value = true;
    try {
      const { data } = await ActionAPI.getFormData({ id });
      return data;
    } catch (error) {
      console.error('Error loading form data:', error);
      ElMessage.error($t('common.message.info.load_failed'));
      throw error;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 提交表单数据（新增）
   * @param {Object} formData - 表单数据
   */
  const addData = async (formData) => {
    loading.value = true;
    try {
      await ActionAPI.add(formData);
    } catch (error) {
      console.error('Error in addHandler:', error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 提交表单数据（更新）
   * @param {Object} formData - 表单数据
   */
  const updateData = async (formData) => {
    loading.value = true;
    try {
      await ActionAPI.update(formData);
      ElMessage.success(
        $t('common.message.success.general', {
          action: $t('common.action.update'),
        }),
      );
    } catch (error) {
      console.error('Error in updateHandler:', error);
      ElMessage.error(
        $t('common.message.failed.general', {
          action: $t('common.action.update'),
        }),
      );
      throw error;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 获取语言键
   * @param {Object} params - 参数对象
   */
  const getLanguageKey = async (params) => {
    try {
      return await ActionAPI.getLanguageKey(params);
    } catch (error) {
      console.error('获取语言键失败:', error);
      throw error;
    }
  };

  return {
    loading,
    getFormData,
    addData,
    updateData,
    getLanguageKey,
  };
}
